#!/usr/bin/python
# -*- coding: utf-8 -*-
# @File    : mylog_set.py
# @Software: PyCharm

import logging
from logging.handlers import RotatingFileHandler
import threading
from conf import settings


class MyLog(object):
    """
    记录日志
    """
    def __init__(self, log_file=settings.LOG_FILE):
        self.log_file = log_file
        self.logger = logging.getLogger(settings.LOGGER_NAME)
        try:
            self.__config_logger()
        except Exception as e:
            print(e)

    def get_logger(self):
        return self.logger

    def __config_logger(self):
        print("config")
        # 设置日志格式
        formatter = logging.Formatter(settings.FMT, datefmt=settings.DATE_FMT)

        if settings.CONSOLE_LOG_ON == 1:  # 如果开启控制台日志

            console = logging.StreamHandler()

            console.setLevel(settings.LOG_LEVEL_IN_CONSOLE)

            console.setFormatter(formatter)
            # if not self._logger.handlers:
            self.logger.addHandler(console)

            self.logger.setLevel(settings.LOG_LEVEL_IN_CONSOLE)

        if settings.FILE_LOG_ON == 1:  # 如果开启文件日志

            rt_file_handler = RotatingFileHandler(self.log_file, maxBytes=settings.MAX_BYTES_EACH,
                                                  backupCount=settings.BACKUP_COUNT, encoding='utf-8')
            rt_file_handler.setFormatter(formatter)
            if not self.logger.handlers:
                self.logger.addHandler(rt_file_handler)

                self.logger.setLevel(settings.LOG_LEVEL_IN_FILE)


mylog = MyLog().get_logger()  # 实例化日志

if __name__ == '__main__':
    mylog.info("test")
    # mylog = MyLog().get_logger()
    # mylog.info("test")
    # mylog.debug("test")
